package lx.scrmXj;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import lx.util.DateUtil;
import lx.util.HttpHelper;
import lx.util.StrUtil;
import oracle.jdbc.driver.DBConversion;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * @Description: 客户信息同步
 * @Author: 李星 lixing_java@163.com
 * @Date: 2020/3/27 16:53
 */
public class CustomerTask extends TimerTask {
    @Override
    public void run() {
        try {
            // 查询本地成员信息
            List<Record> userList = Db.find("SELECT USERID FROM XJ_SCRM_USER");
            int userCount = userList.size();
            System.out.println(MessageFormat.format("{0} 本地成员数量：{1}", DateUtil.dateToDateTimeCharacter(new Date()), userCount));
            // 客户数量多的情况下使用多线程
            ExecutorService executorService = Executors.newFixedThreadPool(20);
            IntStream.range(0, userCount).forEach(i -> {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            selectCustomerIdArray(userList.get(i).getStr("USERID"), i);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 查询外部联系人token
    public String getToken() throws Exception {
        String tokenUrl = "SELECT ACCESS_TOKEN FROM XJ_SCRM_TOKEN where CATEGORY = 2 ORDER BY CREATE_TIME DESC";
        List<Record> recordTokenList = Db.find(tokenUrl);
        String token = recordTokenList.get(0).getStr("ACCESS_TOKEN");
//        System.out.println(MessageFormat.format("{0} 客户信息同步获取token：{1}", DateUtil.dateToDateTimeCharacter(new Date()), token));
        return token;
    }

    // 根据成员编号查询客户编号列表
    public void selectCustomerIdArray(String userid, int index) throws Exception {
        JSONArray customerArray;
        try {
            // 获取客户编号列表
            String customerRes = HttpHelper.sendRequestHttps(
                    MessageFormat.format("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?access_token={0}&userid={1}", getToken(), userid),
                    "GET",
                    null);
            JSONObject customerJson = JSONObject.parseObject(customerRes);
            if (0 == customerJson.getInteger("errcode") && "ok".equals(customerJson.getString("errmsg"))) {
                // 客户编号列表
                customerArray = customerJson.getJSONArray("external_userid");
//                System.out.println(MessageFormat.format("{0} 获取成员（{1}）的客户列表成功：{2}", DateUtil.dateToDateTimeCharacter(new Date()), userid, customerArray.size()));
                // 根据客户编号查询客户详情
                for (int i = 0; i < customerArray.size(); i++) {
                    selectCustomerDetail(customerArray.getString(i), index);
                }
            }
//            else {
//                System.out.println(MessageFormat.format("{0} 获取第{1}个成员（{2}）的客户列表失败：{3}",
//                        DateUtil.dateToDateTimeCharacter(new Date()), index, userid, customerRes));
//            }
        } catch (Exception e) {
            System.out.println(MessageFormat.format("{0} 获取第{1}个成员（{2}）的客户列表出错：{3}",
                    DateUtil.dateToDateTimeCharacter(new Date()), index, userid, e.getMessage()));
        }
    }

    // 根据客户编号查询客户详情信息
    public void selectCustomerDetail(String customerId, int index) throws Exception {
        try {
            String customerDetailRes = HttpHelper.sendRequestHttps(
                    "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=" + getToken() + "&external_userid=" + customerId,
                    "GET",
                    null);
            JSONObject customerDetailJson = JSONObject.parseObject(customerDetailRes);
            if (0 == customerDetailJson.getInteger("errcode") && "ok".equals(customerDetailJson.getString("errmsg"))) {
                /*
                 * @Description TODO 成员列表信息
                 */
                JSONArray follow_user = customerDetailJson.getJSONArray("follow_user");
                /*
                 * @Description TODO 客户详情信息
                 */
                JSONObject external_contact = customerDetailJson.getJSONObject("external_contact");
                external_contact.put("developmentCount", follow_user.size()); // 设置当前客户的成员数量
                //
                //System.out.println(MessageFormat.format("{0} 第{1}个成员 获取客户（{2}）详情成功", DateUtil.dateToDateTimeCharacter(new Date()), index, customerId));
                insertCustomer(external_contact);
                insertCustomerMaintain(follow_user, customerId);
            }
//            else {
//                System.out.println(MessageFormat.format("{0} 第{1}个成员 获取客户（{2}）详情失败：{3}",
//                        DateUtil.dateToDateTimeCharacter(new Date()), index, customerId, customerDetailRes));
//            }
        } catch (Exception e) {
            System.out.println(MessageFormat.format("{0} 第{1}个成员 获取客户（{2}）详情出错：{3}",
                    DateUtil.dateToDateTimeCharacter(new Date()), index, customerId, e.getMessage()));
        }
    }

    // 添加客户信息
    public void insertCustomer(JSONObject external_contact) throws Exception {
        try {
            // 客户信息
            Record customerRecord = new Record();
            customerRecord.set("EXTERNAL_USERID", external_contact.getString("external_userid"));
            customerRecord.set("DEVELOPMENT_COUNT", external_contact.getInteger("developmentCount")); // 当前客户的成员数量
            customerRecord.set("NAME", external_contact.getString("name"));
            customerRecord.set("POSITION", external_contact.getString("position"));
            customerRecord.set("AVATAR", external_contact.getString("avatar"));
            customerRecord.set("CORP_NAME", external_contact.getString("corp_name")); // 所在企业的简称
            customerRecord.set("CORP_FULL_NAME", external_contact.getString("corp_full_name")); // 所在企业的主体名称
            customerRecord.set("TYPE", external_contact.getString("type")); // 外部联系人的类型，1表示该外部联系人是微信用户，2表示该外部联系人是企业微信用户
            customerRecord.set("GENDER", external_contact.getString("gender"));
            customerRecord.set("UNIONID", external_contact.getString("unionid")); // 外部联系人在微信开放平台的唯一身份标识（微信unionid）
            customerRecord.set("EXTERNAL_PROFILE", external_contact.getString("external_profile")); // TODO 外部联系人的自定义展示信息，可以有多个字段和多种类型，包括文本，网页和小程序，仅当联系人类型是企业微信用户时有此字段
            //
            Record customerInfo = Db.findFirst("SELECT EXTERNAL_USERID FROM XJ_SCRM_CUSTOMER WHERE EXTERNAL_USERID = ?", customerRecord.getStr("EXTERNAL_USERID"));
            String operateFlag;
            boolean resultFlag = true;
            if (customerInfo == null) {
                operateFlag = "insert";
                resultFlag = Db.save("XJ_SCRM_CUSTOMER", "EXTERNAL_USERID", customerRecord);
            } else {
                operateFlag = "update";
                // resultFlag = Db.update("XJ_SCRM_CUSTOMER", "EXTERNAL_USERID", customerRecord); // 如果是迭代递增的需求，则次处开启
            }
            System.out.println(MessageFormat.format("{0} {1}客户（{2}）信息结果：{3}",
                    DateUtil.dateToDateTimeCharacter(new Date()), operateFlag, customerRecord.getStr("external_userid"), resultFlag));
        } catch (Exception e) {
            System.out.println(MessageFormat.format("{0} 添加客户（{1}）信息结果：{2}",
                    DateUtil.dateToDateTimeCharacter(new Date()), "", e.getMessage()));
        }
    }

    // 添加客户维系信息
    public void insertCustomerMaintain(JSONArray follow_user, String customerId) throws Exception {
        try {
            // 客户维系信息
            int followUserCount = follow_user.size();
            for (int i = 0; i < followUserCount; i++) {
                Record customerMaintainRecord = new Record();
                customerMaintainRecord.set("EXTERNAL_USERID", customerId);

                String userid = follow_user.getJSONObject(i).getString("userid");
                if (StrUtil.isEffective(userid)) {
                    customerMaintainRecord.set("USERID", userid);
                }

                String remark = follow_user.getJSONObject(i).getString("remark");
                if (StrUtil.isEffective(remark)) {
                    customerMaintainRecord.set("REMARK", remark); // 该成员对此外部联系人的备注
                }

                String description = follow_user.getJSONObject(i).getString("description");
                if (StrUtil.isEffective(description)) {
                    customerMaintainRecord.set("DESCRIPTION", description); // 该成员对此外部联系人的描述
                }

                String remark_corp_name = follow_user.getJSONObject(i).getString("remark_corp_name");
                if (StrUtil.isEffective(remark_corp_name)) {
                    customerMaintainRecord.set("REMARK_CORP_NAME", remark_corp_name); // 该成员对此客户备注的企业名称
                }

                String state = follow_user.getJSONObject(i).getString("state");
                if (StrUtil.isEffective(state)) {
                    customerMaintainRecord.set("STATE", state); // 该成员添加此客户的渠道，由用户通过创建「联系我」方式指定
                }

                String createtime = follow_user.getJSONObject(i).getString("createtime"); // 该成员添加此外部联系人的时间
                if (StrUtil.isEffective(createtime)) {
                    customerMaintainRecord.set("CREATETIME", DateUtil.longTimeToDateTimeStr(Long.parseLong(createtime)));
                }

                JSONArray remark_mobiles_array = follow_user.getJSONObject(i).getJSONArray("remark_mobiles"); // 该成员对此客户备注的手机号码，第三方不可获取
                StringBuilder remark_mobiles = new StringBuilder();
                for (int k = 0; k < remark_mobiles_array.size(); k++) {
                    remark_mobiles.append(remark_mobiles_array.getString(k)).append(",");
                }
                if (StrUtil.isEffective(remark_mobiles.toString())) {
                    customerMaintainRecord.set("REMARK_MOBILES", remark_mobiles.toString());
                }

                JSONArray tags_array = follow_user.getJSONObject(i).getJSONArray("tags"); // 该成员添加此外部联系人所打标签
                StringBuilder group_name = new StringBuilder();
                StringBuilder tag_name = new StringBuilder();
                StringBuilder tag_type = new StringBuilder();
                for (int j = 0; j < tags_array.size(); j++) {
                    group_name.append(tags_array.getJSONObject(j).getString("group_name")).append(",");
                    tag_name.append(tags_array.getJSONObject(j).getString("tag_name")).append(",");
                    tag_type.append(tags_array.getJSONObject(j).getString("type")).append(",");
                }
                if (StrUtil.isEffective(group_name.toString())) {
                    customerMaintainRecord.set("GROUP_NAME", group_name.toString()); // 该成员添加此外部联系人所打标签的分组名称
                }
                if (StrUtil.isEffective(tag_name.toString())) {
                    customerMaintainRecord.set("TAG_NAME", tag_name.toString()); // 该成员添加此外部联系人所打标签名称
                }
                if (StrUtil.isEffective(tag_type.toString())) {
                    customerMaintainRecord.set("TYPE", tag_type.toString()); // 该成员添加此外部联系人所打标签类型, 1-企业设置, 2-用户自定义
                }

                Record customerMaintainInfo = Db.findFirst("SELECT ID FROM XJ_SCRM_CUSTOMER_MAINTAIN WHERE EXTERNAL_USERID = ? AND USERID = ?",
                        customerMaintainRecord.getStr("EXTERNAL_USERID"),
                        customerMaintainRecord.getStr("USERID"));
                String operateFlag;
                boolean resultFlag = true;
                if (customerMaintainInfo == null) {
                    operateFlag = "insert";
                    customerMaintainRecord.set("ID", "XJ_SCRM_COSTOMER_MAINTAIN.nextval"); // TODO 获取指定序列
                    resultFlag = Db.save("XJ_SCRM_CUSTOMER_MAINTAIN", "ID", customerMaintainRecord);
                } else {
                    operateFlag = "update";
                    //customerMaintainRecord.set("ID",customerMaintainInfo.getInt("ID")); // TODO 获取更新条件
                    //resultFlag = Db.update("XJ_SCRM_CUSTOMER_MAINTAIN", "ID", customerMaintainRecord); // 如果是迭代递增的需求，则次处开启
                }
                System.out.println(MessageFormat.format("{0} {1}客户（{2}）维系信息结果：{3}",
                        DateUtil.dateToDateTimeCharacter(new Date()), operateFlag, customerId, resultFlag));
            }
        } catch (Exception e) {
            System.out.println(MessageFormat.format("{0} 添加客户维系信息出错：{1}",
                    DateUtil.dateToDateTimeCharacter(new Date()), e.getMessage()));
        }
    }

}
